package v1

import (
	"database/sql"
	"fmt"
	"log"

	"github.com/tungyao/spruce-light"

	_ "github.com/go-sql-driver/mysql"
)

var (
	DB   *sql.DB
	KVDB *spruce.Hash
)

func init() {
	var errx error
	DB, errx = sql.Open("mysql", fmt.Sprintf("%s:%s@%s(%s:%s)/%s", "root", "1121331", "tcp", "localhost", "3306", "oauth"))
	if errx != nil {
		log.Fatal(errx)
	}
	KVDB = spruce.CreateHash(4096)
	// 在启动时应该去数据全部写入spruce中进行数据预热
	// TODO
	log.Println("loading app")
	loadAppData()
	log.Println("loaded app")
	log.Println("loading user")
	loadUserData()
	log.Println("loaded user")
}
func loadAppData() {
	rows, err := DB.Query("select appid,secret,redirect from app")
	log.Fatalln(err)
	for rows.Next() {
		c := &App{}
		rows.Scan(&c.Appid, &c.Secret, &c.Redirect)
		KVDB.Set(byt("app_"+c.Appid), *c, 0)
	}
	rows.Close()
}
func loadUserData() {
	rows, err := DB.Query("select id,name,pass from user")
	log.Fatalln(err)
	for rows.Next() {
		c := &User{}
		rows.Scan(&c.Id, &c.Name, &c.Pass)
		KVDB.Set(byt("user_"+c.Name), &c, 0)
	}
	rows.Close()
}

// 存储在 spruce中的数据结构

type User struct {
	Id   string
	Name string
	Pass string
}
type App struct {
	Appid    string
	Secret   string
	Redirect string
}
